//
//  CheckButton.m
//  Project
//
//  Created by Suny on 14-10-27.
//  Copyright (c) 2014年 Suny. All rights reserved.
//

#import "CheckButton.h"

#define CHECK_ICON_WH                    (30)
#define ICON_TITLE_MARGIN                (5.0)

@implementation CheckButton

- (id)initWithDelegate:(id <CheckButtonDelegate>)delegate
{
    self = [super init];
    if (self)
    {
        _delegate = delegate;

        self.exclusiveTouch = YES;
        [self setImage:[UIImage imageNamed:@"checkbox1_unchecked.png"]
              forState:UIControlStateNormal];
        [self setImage:[UIImage imageNamed:@"checkbox1_checked.png"]
              forState:UIControlStateSelected];
        [self addTarget:self
                 action:@selector(checkboxBtnChecked)
       forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}

- (void)setChecked:(BOOL)checked
{
    if (_checked == checked)
    {
        return;
    }

    _checked = checked;
    self.selected = checked;

    if (_delegate && [_delegate respondsToSelector:@selector(didSelectedCheckBox:checked:)])
    {
        [_delegate didSelectedCheckBox:self
                               checked:self.selected];
    }
}

- (void)checkboxBtnChecked
{
    self.selected = !self.selected;
    _checked = self.selected;

    if (_delegate && [_delegate respondsToSelector:@selector(didSelectedCheckBox:checked:)])
    {
        [_delegate didSelectedCheckBox:self
                               checked:self.selected];
    }
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    return CGRectMake(0,
                      (CGFloat) ((CGRectGetHeight(contentRect) - CHECK_ICON_WH) / 2.0),
                      CHECK_ICON_WH,
                      CHECK_ICON_WH);
}

- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    return CGRectMake((CGFloat) (CHECK_ICON_WH + ICON_TITLE_MARGIN), 0,
                      (CGFloat) (CGRectGetWidth(contentRect) - CHECK_ICON_WH - ICON_TITLE_MARGIN),
                      CGRectGetHeight(contentRect));
}

- (void)dealloc
{
    _delegate = nil;
}

@end